<?php
namespace app\client\controller;

use app\common\lib\Redis;
use think\swoole\facade\Task;

class MerchantOrder extends Base {
    public function __construct() {
        parent::__construct();
    }
    
    //订单列表
    public function orderList() {
        $userId = $this->userid;
        $params = request()->get();
        $pk = isset($params['lastPk']) ? intval($params['lastPk']) : 0;
        $pageSize = isset($params['pageSize']) ? intval($params['pageSize']) : 20;
        $status = isset($params['status']) ? intval($params['status']) : 0;
        
        $where = [['store_id', '=', $userId], ['status', '=', $status]];
        
        if($pk > 0) {
            $where[] = ['order_id', '<', $pk];
        }
        
        $orderField = ['order_id', 'order_no', 'user_id', 'status', 'quantity', 'amount', 'remarks', 'create_time', 'consignee', 'mobile', 'province', 'city', 'district', 'address'];
    
        $orderList = model('Order')->where($where)->order('order_id desc')->field($orderField)->limit($pageSize)->select()->toArray();
        
        if(!empty($orderList)){
            $orderIds = [];
            $userIds = [];
            foreach ($orderList as $order) {
                array_push($orderIds, $order['order_id']);
                
                $userid = 'user_' . $order['user_id'];
                
                if(!in_array($userid, $userIds)){
                    array_push($userIds, $userid);
                }
                
            }
            
            $redis = new Redis();
            $users = $redis->mget($userIds);
            foreach ($users as $k => $user) {
                $users[$k] = json_decode($user, true);
            }
            
            $orderGoods = model('OrderGoods')->findAll(['order_id' => $orderIds], ['order_id', 'chat_id', 'cover', 'goods_name', 'goods_no', 'price', 'quantity']);
            foreach ($orderList as &$order) {
                $order['goods'] = [];
                
                
                foreach ($users as $user) {
                    if($user['user_id'] == $order['user_id']){
                        $order['user'] = $user;
                        break;
                    }
                }
                
                
                foreach ($orderGoods as $k => $goods) {
                    if($order['order_id'] == $goods['order_id']){
                        array_push($order['goods'], $goods);
                        unset($orderGoods[$k]);
                    }
                }
            }
        }
        
        return successResult(['list' => $orderList]);
    }
    
    public function detail() {
        $orderId = request()->get('id', 0, 'intval');
        if($orderId <= 0){
            return errorResult();
        }
        $orderField = ['user_id', 'order_id', 'order_no', 'status', 'store_id', 'quantity', 'amount', 'remarks', 'delivery_fee', 'pay_status', 'pay_order', 'deliver_order', 'merchant_confirm_time', 'pay_time', 'deliver_time', 'complete_time', 'create_time', 'consignee', 'mobile', 'province', 'city', 'district', 'address'];
        $order = model('Order')->findOne(['order_id' => $orderId], $orderField);
        if(empty($order) || $order['store_id'] != $this->userid){
            return errorResult();
        }
        
        
        $order['user'] = model('User')->findOne(['user_id' => $order['user_id']], ['nickname', 'avatar']);
        $order['user']['user_id'] = $order['user_id'];
        
        $order['goods'] = model('OrderGoods')->findAll(['order_id' => $orderId], ['chat_id', 'cover', 'goods_name', 'goods_no', 'price', 'quantity']);
        
        return successResult(['order' => $order]);
    }
    
    
    //确定订单
    public function confirmOrder() {
        $params = request()->post();
        $orderId = isset($params['id']) ? intval($params['id']) : 0;
        if($orderId <= 0){
            return errorResult();
        }
        
        $fee = isset($params['fee']) ? floatval($params['fee']) : '';
        if($fee < 0){
            return errorResult();
        }
        
        $where = ['order_id' => $orderId];
        
        $model = model('Order');
        
        $model->startTrans();
        
        try {
            $order = $model->where($where)->field(['status', 'store_id', 'user_id'])->lock(true)->find();
            if(empty($order) || $order['store_id'] != $this->userid){
                $model->rollback();
                return errorResult();
            }
            
            if($order['status'] != 0){
                $model->rollback();
                return errorResult($order['status'] == -1 ? '订单已被用户取消' : '确认失败');
                
            }
            
            
            $rs = $model->modify($where, ['status' => 1, 'delivery_fee' => $fee, 'merchant_confirm_time' => time()]);
            if(!$rs) {
                $model->rollback();
                return errorResult('订单确认失败');
            }
            
            $model->commit();
            
            return successResult('确认成功');
            
        } catch (\Exception $e) {
            $model->rollback();
            return errorResult($e->getMessage());
        }
    }
    
    //取消
    public function cancelOrder() {
        $params = request()->post();
        $orderId = isset($params['orderId']) ? intval($params['orderId']) : 0;
        if($orderId <= 0){
            return errorResult();
        }
        
        $where = ['order_id' => $orderId];
        
        $model = model('Order');
        
        $model->startTrans();
        
        try {
            $order = $model->where($where)->field(['status', 'store_id', 'user_id'])->lock(true)->find();
            if(empty($order) || $order['store_id'] != $this->userid){
                $model->rollback();
                return errorResult();
            }
            
            if($order['status'] != 0){
                $model->rollback();
                return errorResult($order['status'] == -1 ? '订单已被用户取消' : '取消失败');
            }
            
            $rs = $model->modify($where, ['status' => -2]);
            if($rs === false) {
                $model->rollback();
                return errorResult('取消订单失败1');
            }
            
            $rs = model('OrderGoods')->where(['order_id' => $orderId])->delete();
            if(!$rs){
                $model->rollback();
                return errorResult('取消订单失败2');
            }
            
            $model->commit();
            
            return successResult('取消成功');
            
        } catch (\Exception $e) {
            $model->rollback();
            return errorResult();
        }
    }
    
    //确定发货
    public function confirmDeliver() {
        $params = request()->post();
        $orderId = isset($params['id']) ? intval($params['id']) : 0;
        if($orderId <= 0) {
            return errorResult();
        }
        
        $deliverOrder = isset($params['order']) ? trim($params['order']) : '';
        if($deliverOrder === '') {
            return errorResult('请上传发货凭证');
        }
        
        $model = model('Order');
        $order = $model->findOne(['order_id' => $orderId], ['store_id', 'status']);
        if(empty($order) || $order['store_id'] != $this->userid) {
            return errorResult();
        }
        
        if($order['status'] != 2) {
            return errorResult('订单未支付');
        }
        
        $rs = $model->modify(['order_id' => $orderId], ['status' => 3, 'deliver_order' => $deliverOrder, 'deliver_time' => time()]);
        if(!$rs){
            return errorResult('操作失败，请稍后重试');
        }
        
        return successResult('确认成功');
        
    }
    
    public function number () {
        $storeId = $this->userid;
        $orderModel = model('Order');
        $number1 = $orderModel->where(['store_id' => $storeId, 'status' => 0])->count(); //等待确认的
        $number2 = $orderModel->where(['store_id' => $storeId, 'status' => 2])->count(); //等发货的
        return successResult(['number1' => $number1, 'number2' => $number2]);
    }
   
}



















